import microApp from '@micro-zoe/micro-app'
import subAppInfo from '@/constant/index'

/**
 * 初始化 micro app
 */
export default function initMicroApp() {
  const isDev = import.meta.env.DEV
  microApp.start({
    plugins: {
      modules: {
        // 子应用的 name
        [subAppInfo.name]: [{
          loader(code) {
            if (isDev) {
              code = code.replace(/(from|import|assets)(\s*['"])(\/child\/vite\/)/g, (all) => {
                const { devServer } = subAppInfo
                const { protocol, hostname } = window.location
                const devUrl = `${protocol}//${hostname}:${devServer.port}${devServer.base}`
                // 换成完整url
                return all.replace(devServer.base, devUrl)
              })
            }
            return code
          }
        }]
      }
    }
  })
}
